package com.abai.doubi.server.interceptor;

import cn.hutool.json.JSONUtil;
import com.abai.doubi.constants.JwtClaimsConstant;
import com.abai.doubi.entity.Result;
import com.abai.doubi.server.properties.JwtProperties;
import com.abai.doubi.utils.ContextUtil;
import com.abai.doubi.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String token;
        // 根据请求方法获取token
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            // GET请求从URL参数中获取令牌
            token = request.getParameter(jwtProperties.getTokenName());
        } else {
            // 非GET请求从请求头中获取令牌
            token = request.getHeader(jwtProperties.getTokenName());
        }        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id:{}", empId);
            ContextUtil.setCurrentId(empId);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            Result result = Result.unauthorized("未登录或登录已过期");
            response.getWriter().write(JSONUtil.toJsonStr(result));
            response.getWriter().flush();
            return false;
        }
    }

    /**
     * 移除threadLocal
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextUtil.removeCurrentId();
    }
}